package com.hxzy.controller.front;

import com.hxzy.common.controller.BaseController;
import com.hxzy.common.enums.AckCode;
import com.hxzy.common.vo.R;
import com.hxzy.dto.OrderDTO;
import com.hxzy.dto.OrderSearch;
import com.hxzy.dto.ShoppingCartSearch;
import com.hxzy.entity.Orders;
import com.hxzy.entity.ShoppingCart;
import com.hxzy.service.OrdersService;
import com.hxzy.service.ShoppingCartService;
import com.hxzy.util.SSMThreadLocal;
import com.hxzy.vo.ContamerLoginVO;
import com.hxzy.vo.OrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 前端用户订单查询
 *
 * @author tonneyyy
 */
@Log4j2
@Api(tags = "前端用户订单API")
@RestController
@RequestMapping(value = "/front/order")
public class FrontOrderController extends BaseController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ShoppingCartService shoppingCartService;

   @ApiOperation(value = "用户最近下的订单")
    @GetMapping(value = "/userPage")
    public R orderPagingApi(OrderSearch orderSearch){
       //得到当前登录前端用户
       ContamerLoginVO contamerLoginVO = SSMThreadLocal.contamerLoginVOThreadLocal.get();
       orderSearch.setUserId(new Long(contamerLoginVO.getId()));

       super.buildPage(orderSearch);
        List<OrderVO> list= this.ordersService.orderPage(orderSearch);
        return R.okHasData(list);
    }


    @ApiOperation(value = "创建订单")
    @PostMapping(value = "/submit")
    public R submit(@RequestBody @Valid OrderDTO orderDTO){

        //得到当前登录前端用户
        ContamerLoginVO contamerLoginVO = SSMThreadLocal.contamerLoginVOThreadLocal.get();

        //得到购物车中的内容
        ShoppingCartSearch shoppingCartSearch=new ShoppingCartSearch();
        shoppingCartSearch.setEnterpriseId(orderDTO.getMid());
        //先前用户
        shoppingCartSearch.setUserId(new Long(contamerLoginVO.getId()));

        List<ShoppingCart> list= this.shoppingCartService.searchByShoppingCart(shoppingCartSearch);
        if(list!=null && list.size()>0){

            long orderId=this.ordersService.submit(orderDTO,list);

            return R.okHasData(orderId);

        }else{
            log.error("购物车中没有订购消息");
            return R.build(AckCode.ORDER_EMPTY);
        }
    }


}
